/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package controller.SRV;

import controller.SRV.*;
import entity.MDoctor;
import entity.SrvCureplan;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;
import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import java.util.ArrayList;
import javax.ejb.EJB;
import session.SrvCureplanFacade;
import util.jQgrid.JQGridFormatterUtil;
import util.jQgrid.JQGridRow;

@WebServlet(name = "SRV_CureplanList",
loadOnStartup = 1,
urlPatterns = {"/SRV/SRV_CureplanList",
    "/SRV/SRV_CureplanList/grd_search"})
public class SRV_CureplanList extends HttpServlet {

    private String sampleServletContext;
    @EJB
    SrvCureplanFacade srvCureplanFacade;

    @Override
    public void init(ServletConfig servletConfig) throws ServletException {

        super.init(servletConfig);

        // initialize servlet with configuration information
        sampleServletContext = servletConfig.getServletContext().getInitParameter("sampleServletContext");
    }

    /**
     * Handles the HTTP <code>GET</code> method.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {

        String userPath = request.getServletPath();
        HttpSession session = request.getSession();

        // if category page is requested
        if (userPath.equals("/Srv/SRV_CureplanList")) {
            userPath = "/Srv/SRV_CureplanList";
        }

        // use RequestDispatcher to forward request internally
        String url = "/WEB-INF/view" + userPath + ".jsp";

        try {
            request.getRequestDispatcher(url).forward(request, response);
        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }

    /**
     * Handles the HTTP <code>POST</code> method.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        request.setCharacterEncoding("UTF-8");  // ensures that user input is interpreted as
        // 8-bit Unicode (e.g., for Czech characters)
        Boolean isDispatcher = true; //กำหนดว่า ต้องการให้เปลี่ยนหน้าหรือไม่ ? ต้องการ : ไม่ต้องการ
        String userPath = request.getServletPath();
        HttpSession session = request.getSession();


        if (userPath.equals("/SRV/SRV_CureplanList/grd_search")) {
            response.setContentType("text/json");
            String qstr_page = request.getParameter("page"); // get the requested page
            String qstr_limit = request.getParameter("rows"); // get how many rows we want to have into the grid
            String qstr_sidx = request.getParameter("sidx"); // get index row - i.e. user click to sort
            String qstr_sord = request.getParameter("sord"); // get the direction

            if (qstr_sidx.isEmpty()) {
                qstr_sidx = "id";
                qstr_sord = "asc";
            }

            String txtName = (request.getParameter("txtName") != null) ? request.getParameter("txtName") : "";
            String txtPrice = (request.getParameter("txtPrice") != null) ? request.getParameter("txtPrice") : "";
            String txtCurrency = (request.getParameter("txtCurrency") != null) ? request.getParameter("txtCurrency") : "";
            String txtDoctorName = (request.getParameter("txtDoctorName") != null) ? request.getParameter("txtDoctorName") : "";
            String ddlStatus = (request.getParameter("ddlStatus") != null) ? request.getParameter("ddlStatus") : "";
           
            PrintWriter out = response.getWriter();
            List<SrvCureplan> lSrvCureplan;
            List rows;
            JQGridRow row;
            List cells;
            String strJson = "";
            int totalRecords = 0;
            int endList = Integer.parseInt(qstr_limit)*Integer.parseInt(qstr_page);
            int startList = Integer.parseInt(qstr_limit)*Integer.parseInt(qstr_page) - Integer.parseInt(qstr_limit);
            try {
                //Query Java Object
                lSrvCureplan = srvCureplanFacade.LoadDataCurePlan(txtName, txtPrice, txtCurrency, txtDoctorName, ddlStatus, qstr_sidx ,qstr_sord);
                totalRecords = lSrvCureplan.size();
                if (endList>totalRecords){
                    endList=totalRecords;
                }
                //Use List rows
                rows = new ArrayList();
                if (!lSrvCureplan.isEmpty()) {
                    for (SrvCureplan obj : lSrvCureplan.subList(startList, endList)) {
                        row = new JQGridRow();
                        row.setId(obj.getId());

                        cells = new ArrayList();
                        cells.add(obj.getId().toString());
                        cells.add(obj.getSrvCureservice().getName());
                        cells.add(obj.getSrvCureservice().getPrice().toString());
                        cells.add(obj.getSrvCureservice().getCurrency());
                        if (obj.getSrvCureservice().getMDoctor() != null) {
                            cells.add(obj.getSrvCureservice().getMDoctor().getName() + " " + obj.getSrvCureservice().getMDoctor().getSurname());
                        } else {
                            cells.add("");
                        }
                        if (obj.getSrvCureservice().getMHospital() != null) {
                            cells.add(obj.getSrvCureservice().getMHospital().getName());
                        } else {
                            cells.add("");
                        }
                        String strStatus = controller.enumConstant.StatusConstant.valueOf(obj.getStatus().toString()).getStatus();
                        cells.add(strStatus);

                        row.setCell(cells);
                        rows.add(row);
                    }
                }

                strJson = JQGridFormatterUtil.getJSON(Integer.parseInt(qstr_page), Integer.parseInt(qstr_limit), totalRecords, rows);
                out.println(strJson);
            } catch (Exception ex) {
                System.out.println("Error message" + ex.getMessage());
            } finally {
                out.close();
                lSrvCureplan = null;
                rows = null;
                row = null;
                cells = null;
                strJson = null;
            }

            isDispatcher = false;
        }

        // use RequestDispatcher to forward request internally
        String url = "/WEB-INF/view" + userPath + ".jsp";

        try {
            if (isDispatcher) {
                request.getRequestDispatcher(url).forward(request, response);
            }
        } catch (Exception ex) {
            ex.printStackTrace();

        }

    }
}
